package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户提交订单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        // 判断购物车是否为空
        // 构建购物车对象 用于查询当前用户购物车信息
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(BaseContext.getCurrentId())
                .build();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectByMany(shoppingCart);
        if (shoppingCarts == null || shoppingCarts.size() <= 0) {
            // 此时购物车为空 不能提交订单
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 判断当前订单对应的地址是否为空
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            // 当前用户填写的地址 在数据库中不存在
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 插入订单信息
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(System.currentTimeMillis() + ""); // 生成订单号
        orders.setUserId(BaseContext.getCurrentId());   // 下单用户
        orders.setOrderTime(LocalDateTime.now());

        // 订单支付状态和订单状态
        orders.setStatus(Orders.PENDING_PAYMENT); // 设置订单状态为待付款
        orders.setPayStatus(Orders.UN_PAID); // 支付状态

        // 订单配送信息
        orders.setAddress(addressBook.getDetail()); // 收获地址
        orders.setPhone(addressBook.getPhone()); // 收获手机号
        orders.setConsignee(addressBook.getConsignee()); // 收货人

        orderMapper.insertOrder(orders);

        // 插入订单明细信息
        // 遍历购物车中的信息 设置好订单id字段后 批量插入订单明细表中
        List<OrderDetail> orderDetails = shoppingCarts.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail);
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailMapper.insertOrderDetails(orderDetails);

        // 清空购物车
        shoppingCartMapper.deleteShoppingCart(shoppingCart);

        // 响应订单vo数据
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        return orderSubmitVO;
    }

    /**
     * 修改订单状态
     * @param ordersPaymentDTO
     */
    @Override
    public void paymentOrder(OrdersPaymentDTO ordersPaymentDTO) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        Orders orderDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);


        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(orderDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .payMethod(ordersPaymentDTO.getPayMethod())
                .build();

        orderMapper.updateOrderStatus(orders);

        // 通过websocket 通知商家来订单了 并将订单信息封装入map
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "订单号:" + ordersPaymentDTO.getOrderNumber());
        // 将信息 转为 json字符串 调用websocket业务
        String re = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(re);
    }

    /**
     * 用户查询历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageListOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 设置当前用户id
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());

        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 根据条件查询订单基本信息
        List<Orders> orders = orderMapper.selectOrder(ordersPageQueryDTO);
        // 将查询出的套餐基本信息分页
        Page<Orders> page = (Page<Orders>) orders;
        // 遍历分页后的结果 进行进一步封装 将订单详情信息封装
        List<OrderVO> orderVOS = page.stream().map(order -> {
            // 创建vo对象 封装订单基本信息和详情信息
            OrderVO orderVO = new OrderVO();
            // 将订单基本信息拷贝给vo对象
            BeanUtils.copyProperties(order, orderVO);
            // 封装该订单对应的详细信息
            List<OrderDetail> orderDetails = orderDetailMapper.selectDetailById(order.getId());
            orderVO.setOrderDetailList(orderDetails);
            return orderVO;
        }).collect(Collectors.toList());

        return new PageResult(page.getTotal(), orderVOS);
    }

    /**
     * 用户查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetail(Long id) {
        // 根据订单id 查询订单基本信息
        Orders order = orderMapper.selectOrderById(id);
        // 创建vo对象 封装套餐基本信息 并拷贝给vo对象
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);

        // 查询出当前订单对应的订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.selectDetailById(id);
        // 封装后返回数据
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void againOrder(Long id) {
        // 根据订单id 查询当前订单有哪些菜品
        List<OrderDetail> orderDetails = orderDetailMapper.selectDetailById(id);

        // 遍历出菜品 拷贝给购物车对象 并放入购物车中
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insertShoppingCart(shoppingCart);
        }
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 根据用户当前催单的id 查询出当前订单所有信息
        Orders orders = orderMapper.selectOrderById(id);
        // 判断如果为空 则抛出异常
        if (orders == null) {
            throw new OrderBusinessException("用户不存在");
        }
        // 不为空  封装当前订单的数据
        Map<String, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        // 将数据转为json字符串 并调用websocket服务
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }

    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        // 构建查询条件
        Orders orders = Orders.builder()
                .id(id)
                .userId(null)
                .cancelReason("用户取消了订单")
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .build();
        // 执行修改
        orderMapper.updateOrderStatus(orders);
    }

    /**
     * 统计各个状态的订单数量
     * @return
     */
    @Override
    public OrderStatisticsVO orderStatistics() {

        // 待接单数量
        Integer toBeConfirmed = orderMapper.selectCountByStatistics(Orders.TO_BE_CONFIRMED);

        // 待派送数量
        Integer confirmed = orderMapper.selectCountByStatistics(Orders.CONFIRMED);

        // 派送中数量
        Integer deliveryInProgress = orderMapper.selectCountByStatistics(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

}
